#
# from http import HTTPStatus
# from urllib.parse import urlparse, unquote
# from pathlib import PurePosixPath
# import requests
# from dashscope import ImageSynthesis
# import os
#
# prompt = "一间有着精致窗户的花店，漂亮的木质门，摆放着花朵"
#
#
# print('----sync call, please wait a moment----')
# rsp = ImageSynthesis.call(api_key=os.getenv("DASHSCOPE_API_KEY"),
#                           model="wanx2.1-t2i-turbo",
#                           prompt=prompt,
#                           n=1,
#                           size='1024*1024')
# print('response: %s' % rsp)
# if rsp.status_code == HTTPStatus.OK:
#     # 在当前目录下保存图片
#     for result in rsp.output.results:
#         file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
#         with open('./%s' % file_name, 'wb+') as f:
#             f.write(requests.get(result.url).content)
# else:
#     print('sync_call Failed, status_code: %s, code: %s, message: %s' %
#           (rsp.status_code, rsp.code, rsp.message))

'''
ti 2 i
虚拟模特
https://tongyi.aliyun.com/wanxiang/app/virtual-model?spm=a2c4g.11186623.0.0.5764408dCoDxXI
https://help.aliyun.com/zh/model-studio/user-guide/virtual-model-generation?spm=a2c4g.11186623.help-menu-2400256.d_1_0_6_4.4d38b0a8uxZKnV&scm=20140722.H_2849497._.OR_help-T_cn~zh-V_1#26c0acd510syp
'''

import os.path

import requests

import cv2
import json
import numpy as np

import base64

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def create_mask_from_labelme(json_path, output_path):
    """
    根据LabelMe标注生成mask图像。

    :param json_path: LabelMe JSON文件路径。
    :param output_path: 输出mask图像的路径。
    :param image_shape: 目标mask图像的尺寸(height, width)。
    """
    # 读取json文件
    with open(json_path, 'r') as f:
        data = json.load(f)

    # 创建一个全0的mask图像
    image_shape = data['imageHeight'],data['imageWidth']
    mask = np.zeros(image_shape, dtype=np.uint8)
    # 遍历shapes(标注区域)
    for shape in data['shapes']:
        # 获取多边形的点
        points = np.array(shape['points'], dtype=np.int32)

        # 绘制填充多边形到mask上
        cv2.fillPoly(mask, [points], color=255)  # 使用255填充

    # 保存mask图像
    cv2.imwrite(output_path, mask)
img_path = r"D:\code\other\LLMs\algorithms\remote_infer\wxtp_20250314173449.jpg"
img_path = r"https://broadscope-wanxiang-new.oss-cn-beijing.aliyuncs.com/wanx/1738825120220220787/virtual_model/bb3c032a2200487588944da7b221ebef_3.png?Expires=1744788121&OSSAccessKeyId=LTAI5tFx57Ahw5SVArLDePLJ&Signature=ECBDIPk0B7O3G9wujfEFk0%2BpsAA%3D&response-content-disposition=attachment&x-oss-process=image%2Fwatermark%2Cimage_aW1nL-S4h-ebuOWFqOmDqOWPjeeZveeJiOacrEAyeC5wbmc_eC1vc3MtcHJvY2Vzcz1pbWFnZS9yZXNpemUsUF8yMA%2Ct_80%2Cg_se%2Cx_30%2Cy_30%2Fformat%2Cwebp"
# img = cv2.imread(img_path)
json_file_path =  r"D:\code\other\LLMs\algorithms\remote_infer\wxtp_20250314173449.json"
output_mask_image_path = r"D:\code\other\LLMs\algorithms\remote_infer\mask_wxtp_20250314173449.jpg"
if not os.path.exists(output_mask_image_path):
    create_mask_from_labelme(json_file_path, output_mask_image_path)

# API URL
url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation"
YOUR_DASHSCOPE_API_KEY = 'sk-38bdbf76aba641dfb1a671c7259d6dd5'
# 请求头
headers = {
    'X-DashScope-Async': 'enable',  # 异步调用
    'Authorization': f'Bearer {YOUR_DASHSCOPE_API_KEY}',  # 替换为你的API密钥
    'Content-Type': 'application/json'
}
if True:
    # 请求体
    # t1 = r'https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/7749386271/p850516.png'
    data = {
        "model": "virtualmodel-v2",
        "input": {
            "base_image_url": image_to_base64(img_path),  # 原始图片URL
            "mask_image_url": image_to_base64(output_mask_image_path),  # 遮罩图片URL
            "prompt": "a beautiful chinese woman stands in front of a plain white background",
            "face_prompt": "a beautiful chinese woman, good face, best face, best quality"
        },
        "parameters": {
            "short_side_size": "1024",
            "n": 2
        }
    }

    # 发送POST请求
    print('发送POST请求')
    response = requests.post(url, headers=headers, json=data)

    # 检查响应状态码并处理响应
    if response.status_code == 200:
        print("请求成功")
        print(response.json())  # 输出响应内容
    else:
        print(f"请求失败，状态码: {response.status_code}")
        print(response.text)  # 输出错误信息




# task_id = response.json()['output']['task_id'] # 'task_id': '2fbb5f7a-5c2d-449d-bdc5-7b2b82f946c8'
# # task_id = '2fbb5f7a-5c2d-449d-bdc5-7b2b82f946c8'
# # API URL
# url = f"https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}"
# # 请求头
# headers = {
#     'Authorization': f'Bearer {YOUR_DASHSCOPE_API_KEY}'
# }
#
# # 发送GET请求
# response = requests.get(url, headers=headers)
# # 检查响应状态码并处理响应
# if response.status_code == 200:
#     print("请求成功")
#     print(response.json())  # 输出响应内容
# else:
#     print(f"请求失败，状态码: {response.status_code}")
#     print(response.text)  # 输出错误信息